/* Filename: mydate.c
 * Description: 指定参数格式化显示当前时间
 *   ./mydate -Y4 -mdH12  # 2025 02 18 09(P)
 * Last modified: humble 20250218 21:56
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define BUFSIZE (1024)
#define STRFMTSIZE (1024)
static void usage(void);

int main(int argc, char **argv) {
    FILE *fp = stdout;
    char buf[BUFSIZE] = {0};
    char strfmt[STRFMTSIZE] = {0};
    int opt = 0;

    time_t stamp = time(NULL); // 获取当前时间戳
    if(stamp == (time_t)-1){ perror("time"); exit(1); }

    struct tm *tmptr = localtime(&stamp); // 时间戳转时间结构体
    if(!tmptr){ perror("localtime"); exit(1); }

    while(1){
        opt = getopt(argc, argv, "-Y:mdH:MS");
        if(opt < 0){ usage(); break; }
        switch(opt){
            case 1:
                if(fp == stdout){
                    if(NULL == (fp = fopen(argv[optind -1], "w"))){
                        perror("fopen");
                        fp = stdout;
                    }
                }
                break;
            case 'Y':
                if(!strcmp(optarg, "2")){ strncat(strfmt, "%y ", STRFMTSIZE); }
                else if(!strcmp(optarg, "4")){ strncat(strfmt, "%Y ", STRFMTSIZE); }
                else{ fprintf(stderr, "invalid yearopt:%s\n", optarg); }
                break;
            case 'm':
                strncat(strfmt, "%m ", STRFMTSIZE);
                break;
            case 'd':
                strncat(strfmt, "%d ", STRFMTSIZE);
                break;
            case 'H':
                if(!strcmp(optarg, "12")){ strncat(strfmt, "%I(%P) ", STRFMTSIZE); }
                else if(!strcmp(optarg, "24")){ strncat(strfmt, "%H ", STRFMTSIZE); }
                else{ fprintf(stderr, "invalid Houropt:%s\n", optarg); }
                break;
            case 'M':
                strncat(strfmt, "%M ", STRFMTSIZE);
                break;
            case 'S':
                strncat(strfmt, "%S ", STRFMTSIZE);
                break;
            default:
                usage();
                break;
        }

    }
    // 把时间结构体tmptr根据strfmt格式化保存到buf[BUFSIZE]内
    strftime(buf, BUFSIZE, strfmt, tmptr);
    fputs(buf, fp);
    if(fp != stdout){ fclose(fp); }
    return 0;
}

static void usage(void) {
#define USAGE "Usage:\n\
  mydate\n\
    -Y <2|4>:year\n\
    -m :month\n\
    -d :date\n\
    -H <12:24>:Hour\n\
    -M :Minite\n\
    -S :Second\n"
    printf(USAGE);
}
